package com.hqx.shiro.controller;

import com.hqx.shiro.base.BaseResult;
import com.hqx.shiro.req.LoginReq;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LoginController
 * @Description
 * @Author ph
 * @Date 2019/7/26 0:30
 * @Version 1.0
 **/
@Controller
@RequestMapping("/pub")
public class LoginController {

    @RequestMapping("/needLogin")
    @ResponseBody
    public BaseResult needLogin(){

        return BaseResult.error(-2,"这是登录页面====温馨提示：请使用对应的账号登录");

    }


    @RequestMapping("/notPermit")
    @ResponseBody
    public BaseResult notPermit(){
        return BaseResult.error(-3,"温馨提示：拒绝访问，没权限");
    }


    /**
     * 登录接口
     * @param req
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public BaseResult login(@RequestBody LoginReq req, HttpServletRequest request, HttpServletResponse response){

        Subject subject = SecurityUtils.getSubject();
        Map<String,Object> info = new HashMap<>(2);
        try {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(req.getName(), req.getPwd());

            subject.login(usernamePasswordToken);

            info.put("token", subject.getSession().getId());

            return BaseResult.success("登录成功",info);

        }catch (Exception e){
            e.printStackTrace();

            return BaseResult.error("账号或者密码错误");

        }


    }




}
